In [1]:
s=set() #this is how you create a set
s.add(5) #this is how you add items to sets
s.add("hi")
s.add(5)
s.add("ho")
s.add("hi")
s1=set([1,2,3,4,5]) #and you can also create sets from lists or any other iterables
s2=set([4,5,6,7])
#sets allow basic set operations
print("s1",s1)
print("s2",s2)
print("s1&s2",s1&s2) #intersection
print("s1-s2",s1-s2) #difference
print("s1|s2",s1|s2) #union
print("s1 before union update",s1)
s1.update(s2)#union in-place
print("s1 after union update",s1)
Set.remove() causes an error in case the item is not there.
In [2]:
s1.remove(11)
In [3]:
import traceback #needed if we want to print the error
try:
#Code to run
s1.remove(11)
except KeyError: #react on key errors
#Code to run at the moment when an error happens in between try and except
print("Error. Happened. I'm inside except!")
traceback.print_exc() #print the erorr (note - iPython notebook catches this and turns into the red block seemingly in the wrong place)
#error processed now, program continues
print("woohoo made it to the end")
In [ ]: